package com.cy.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Value("${spring.application.name}")
    private String appName;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/consumer/doRestEcho")
    public String doRestEcho(){
        ServiceInstance serviceInstance =
                loadBalancerClient.choose("nacos-provider");//需要调用的服务
        String url = String.format("http://%s:%s/provider/doecho/%s",//拼接调用服务网址
                serviceInstance.getHost(),
                serviceInstance.getPort(),
                appName);
        System.out.println("request url:"+url);
        return restTemplate.getForObject(url, String.class);
    }
}

